package wisents.wicket;

import org.apache.wicket.Session;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.apache.wicket.util.tester.WicketTester;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import wisents.api.WisentsTestBase;

import java.util.Locale;

/**
 * Created by IntelliJ IDEA.
 * User: rabbit
 * Date: Jan 29, 2010
 * Time: 7:14:48 PM
 * To change this template use File | Settings | File Templates.
 */
public class WisentsWicketTestBase extends WisentsTestBase {

    @Autowired
    protected ApplicationContext applicationContext;

    protected SpringComponentInjector injector;

    protected WicketTester tester;

    public void init() {
        populateData();
        createTester();
    }

    private void createTester() {
        tester = new WicketTester((WebApplication) applicationContext.getBean("wicketApplication"));
        tester.setupRequestAndResponse();
        tester.getWicketSession().setLocale(getLocale());

        if (isIntegrationTest()) {
            injector = new SpringComponentInjector(tester.getApplication(), applicationContext, true);
            injector = new SpringComponentInjector(tester.getApplication(), applicationContext, true);
        } else {
            injector = new WisentsSpringComponentInjector(tester.getApplication(), applicationContext, true);
        }


        tester.getApplication().addComponentInstantiationListener(
                injector);
        initSessionBeforeTest(tester.getWicketSession());
        WicketVendor.getWicketVendorInstance().setTesters(tester);
    }


    public boolean isIntegrationTest() {
        return false;
    }


    /**
     * Override to change locale
     *
     * @return locale, default PL
     */
    protected Locale getLocale() {
        return new Locale("PL");
    }

    /**
     * Insert application specific properties to session, run methods on session ect.
     *
     * @param session
     */
    protected void initSessionBeforeTest(Session session) {
        // to be override in test if nesseccary
    }

    /**
     * Override to populate data in database for each test
     */
    protected void populateData() {
        // to be override in test if nesseccary
    }

}
